﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleBuffer
{
    internal class BufferedConsole : IDisposable
    {
        private static int defaultBufferSize;
        private StringBuilder buffer;
        private int bufferSize;

        static BufferedConsole()
        {
            defaultBufferSize = 25;
        }

        public BufferedConsole()
        {
            bufferSize = defaultBufferSize;
            buffer = new StringBuilder(defaultBufferSize);
        }

        private void Flush()
        {
            while (ShouldWrite())
            {
                for (int i = 0; i < bufferSize; i++)
                {
                    Console.Write(buffer[i]);
                }

                buffer.Remove(0, bufferSize);
            }
        }

        private bool ShouldWrite()
        {
            return buffer.Length >= bufferSize;
        }

        public void Write(string message)
        {
            buffer.Append(message);
            Flush();
        }

        public void WriteLine(string message)
        {
            buffer.Append(message);
            buffer.Append(Environment.NewLine);
            Flush();
        }

        ~BufferedConsole()
        {
            Dispose(false);
        }

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        private void Dispose(bool disposing)
        {
            Console.WriteLine(buffer);
        }
    }
}
